//
//  UIImage+AsyncDraw.swift
//  03.照片选择器
//
//  Created by yaochunlin on 16/4/27.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit
//异步等比例缩放图片
extension UIImage {

    //异步绘制图片
    func ycl_AsyncDrawImage(var size: CGSize? , bgColor: UIColor? = UIColor.whiteColor(), isCorner: Bool = false, drawFinish:(image:UIImage?) -> ()) {
        
        dispatch_async(dispatch_get_global_queue(0, 0)) { 
            
            //如果别人没有传入size
            if size == nil {
            
                //采用图片的大小
                size = self.size
            }
            
            //上下文大小的rect
            let rect = CGRect.init(origin: CGPointZero, size: size!)
            
            //开启图形上下文
            UIGraphicsBeginImageContextWithOptions(size!, bgColor != nil, UIScreen.mainScreen().scale)
            
            //设置背景颜色
            bgColor?.setFill()
            UIRectFill(rect)
            
            //需要圆角
            if isCorner {
            
                let path = UIBezierPath.init(ovalInRect: rect)
                
                //让后面绘制的元素在路径里面
                path.addClip()
            }
            
            self.drawInRect(rect)
            
            //获取新图片
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            
            dispatch_async(dispatch_get_main_queue(), { 
                
                drawFinish(image: newImage)
            })
        }
        
    }
}
